from flask import Flask, render_template, request, url_for, flash, redirect, session
import sqlite3

# static_url_path='/' 指定样式文件位置
app = Flask(__name__, static_url_path='/')
# 设置密钥 用于加密请求
app.config['SECRET_KEY'] = 'rskill|renhang0203@88.com'


# 创建方法获取数据库连接
def get_db_connection():
    conn = sqlite3.connect('database.db')
    # 数据库查出来的数据当字典来用
    conn.row_factory = sqlite3.Row
    return conn


# 查询文章
def get_post(post_id):
    conn = get_db_connection()
    post = conn.execute('select * from posts where id =?', (post_id,)).fetchone()
    return post


# # 从数据库去获取管理员信息用来比较
def get_user():
    conn = get_db_connection()
    user = conn.execute('select * from user where id =1').fetchone()
    return user


# 主页 index
@app.route('/index.html')
@app.route('/index')
@app.route('/')
def index():
    # 调用数据库方法
    conn = get_db_connection()
    posts = conn.execute('select * from posts order by created desc').fetchall()
    # order by created desc 倒排序 使得新建文章显示在最上方
    return render_template('index.html', posts=posts)


#  调用gte_post()方法查询文章id,返回文章详情页
@app.route('/posts/<int:post_id>')
#   <int:post_id> 表示参数可变的量,类型为整型
def post(post_id):
    post = get_post(post_id)
    return render_template('post.html', post=post)


# 登录页面
@app.route('/login', methods=['GET', 'POST'])
def login():
    # 先判断是否是已经登录过了的
    user_info = session.get('user_info')
    if user_info is not None:
        return redirect('/admin')
    # 如果是get请求 session['user_info']没有值就返回login页面
    if request.method == 'GET':
        return render_template('login.html')
    # 获取表单传过来的用户名和密码
    username = request.form.get('user')
    password = request.form.get('pass')
    # 将前端输入和从数据库取到的字段值做对比进行判断
    if get_user()['username'] == username  and get_user()['password']== password:
        # 给session赋值 目的是 区分登录和未登录
        session['user_info'] = username
        return redirect('/admin')
    else:
        return render_template('login.html')


# 后台
@app.route('/admin', methods=['GET', 'POST'])
def admin():
    # user_info 用来判断用户是否是从登录页面进行登录
    # 如果直接方法 admin 路径 这时的 user_info 为 None ,return 到 login页
    # user_info 有值的话 进入后台
    user_info = session.get('user_info')
    if user_info is None:
        return render_template('login.html')
    users = get_user()
    # 查询文章id
    conn = get_db_connection()
    posts = conn.execute('select * from posts order by created desc').fetchall()
    return render_template('admin.html', posts=posts, users=users)


# 退出登录状态
@app.route('/logout')
def logout():
    # 清除session
    del session['user_info']
    # 返回主页
    return redirect('/')


#  新建文章
@app.route('/admin/new', methods=('GET', 'POST'))
def new():
    # 验证身份
    user_info = session.get('user_info')
    if user_info is None:
        return render_template('login.html')

    elif request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        sketch = request.form['sketch']
        picture = request.form['picture']

        if not title:
            flash('标题不能为空!')
        elif not content:
            flash('内容不能为空')
        else:
            conn = get_db_connection()
            conn.execute('INSERT INTO posts (title, content , sketch ,picture) VALUES (?, ?, ?, ?)',
                         (title, content, sketch, picture))
            conn.commit()
            conn.close()
            return redirect(url_for('admin'))

    return render_template('new.html')


# 文章修改页面
@app.route('/admin/edit/<int:id>', methods=('GET', 'POST'))
def edit(id):
    # 验证身份
    user_info = session.get('user_info')
    if user_info == 'None':
        return render_template('login.html')

    post = get_post(id)
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        sketch = request.form['sketch']
        picture = request.form['picture']

        if not title:
            return render_template(url_for('index'))
        else:
            conn = get_db_connection()
            conn.execute('update posts SET title=?,content=?,sketch=?,picture=?'
                         ' where id=?', (title, content, sketch, picture, id))
            conn.commit()
            conn.close()
            return redirect(url_for('admin'))

    return render_template('edit.html', post=post)


# 文章删除
@app.route('/admin/<int:id>/delt/', methods=['GET', 'POST'])
def delt(id):
    # 验证身份
    user_info = session.get('user_info')
    if user_info is None:
        return render_template('login.html')
    elif request.method == 'GET':
        return render_template('index.html')
    elif request.method == 'POST':
        post = get_post(id)
        # 连接数据库
        conn = get_db_connection()
        # 执行删除语句
        conn.execute('DELETE FROM posts WHERE id = ?', (id,))
        conn.commit()
        conn.close()
        flash('"{}"删除成功！'.format(post['title']))
        return redirect(url_for('admin'))


# 关于页面
@app.route('/about')
def about():
    return render_template('about.html')


if __name__ == '__main__':
    # 运行Flask应用(启动Flask的服务)，默认在本机开启的端口号是5000.
    # debug=True,是将当前的启动模式改为调试模式(开发环境中建议使用调试模式，生产环境中不允许使用)
    app.run(debug=True, port=4000)
